package com.lizicloud.infrastructure.common.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 缓存工具类
 */
public class CacheUtils {
    
    private static final Map<String, Object> CACHE = new ConcurrentHashMap<>();
    private static final Map<String, Long> EXPIRE_TIME = new ConcurrentHashMap<>();
    
    /**
     * 放入缓存
     */
    public static void put(String key, Object value) {
        put(key, value, -1);
    }
    
    /**
     * 放入缓存（带过期时间，单位：秒）
     */
    public static void put(String key, Object value, long expireSeconds) {
        CACHE.put(key, value);
        if (expireSeconds > 0) {
            EXPIRE_TIME.put(key, System.currentTimeMillis() + expireSeconds * 1000);
        } else {
            EXPIRE_TIME.remove(key);
        }
    }
    
    /**
     * 获取缓存
     */
    @SuppressWarnings("unchecked")
    public static <T> T get(String key) {
        if (isExpired(key)) {
            remove(key);
            return null;
        }
        return (T) CACHE.get(key);
    }
    
    /**
     * 移除缓存
     */
    public static void remove(String key) {
        CACHE.remove(key);
        EXPIRE_TIME.remove(key);
    }
    
    /**
     * 清空缓存
     */
    public static void clear() {
        CACHE.clear();
        EXPIRE_TIME.clear();
    }
    
    /**
     * 检查缓存是否存在
     */
    public static boolean contains(String key) {
        if (isExpired(key)) {
            remove(key);
            return false;
        }
        return CACHE.containsKey(key);
    }
    
    /**
     * 检查是否过期
     */
    private static boolean isExpired(String key) {
        Long expireTime = EXPIRE_TIME.get(key);
        if (expireTime == null) {
            return false;
        }
        return System.currentTimeMillis() > expireTime;
    }
    
    /**
     * 获取缓存大小
     */
    public static int size() {
        return CACHE.size();
    }
    
    /**
     * 获取所有缓存键
     */
    public static Map<String, Object> getAll() {
        Map<String, Object> result = new HashMap<>();
        for (String key : CACHE.keySet()) {
            if (!isExpired(key)) {
                result.put(key, CACHE.get(key));
            } else {
                remove(key);
            }
        }
        return result;
    }
    
    private CacheUtils() {
        // 私有构造函数，防止实例化
    }
}